//
//  HZTXferManager.m
//  HZTrip
//
//  Created by WangChengwen on 10/22/14.
//  Copyright (c) 2014 hztrip.org. All rights reserved.
//

#import "HZTXferManager.h"
#import "Constants.h"
#import "DebugLog.h"
#import "HZTStationInfo.h"
#import "HZTBikeStationManager.h"


NSString *const kNotificationCircumInfoGetSuccess = @"kNotificationCircumInfoGetSuccess";
NSString *const kNotificationCircumInfoGetFailed = @"kNotificationCircumInfoGetFailed";

NSString *const kNotificationStationInfoGetSuccess = @"kNotificationStationInfoGetSuccess";
NSString *const kNotificationStationInfoGetFailed = @"kNotificationStationInfoGetFailed";


@implementation HZTXferManager

+ (instancetype)sharedManager
{
    static HZTXferManager *sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[self alloc] init];
    });
    
    return sharedManager;
}

- (instancetype)init
{
    if (self = [super init]) {
        
    }
    
    return self;
}


- (void)getCircumInfo:(double)latitude longitude:(double)longitude radius:(int)radius
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/bike/around?lat=%f&lon=%f&count=30", ServerURL, latitude, longitude]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setTimeoutInterval:10.0];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) {
            DebugLog(@"Httperror:%@%ld", connectionError.localizedDescription, connectionError.code);
            
        }
        else
        {
            NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@", responseString);
            
            @try {
                NSArray *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                NSMutableDictionary *tempDict = [NSMutableDictionary dictionaryWithCapacity:result.count];
                for (NSDictionary *stationDict in result) {
                    HZTStationInfo *stationInfo = [[HZTStationInfo alloc] init];
                    stationInfo.stationID = [(NSNumber *)stationDict[@"id"] stringValue];
                    stationInfo.address = stationDict[@"info"][@"address"];
                    stationInfo.city = stationDict[@"info"][@"city"];
                    stationInfo.tags = stationDict[@"info"][@"tags"];
                    stationInfo.isAllDay = [stationDict[@"info"][@"isAllDay"] boolValue];
                    stationInfo.isOnDuty = [stationDict[@"info"][@"isOnDuty"] boolValue];
                    stationInfo.serviceTime = stationDict[@"info"][@"serviceTime"];
                    stationInfo.telephone = stationDict[@"info"][@"telephone"];
                    stationInfo.title = stationDict[@"info"][@"title"];
                    stationInfo.distance = [stationDict[@"info"][@"distance"] integerValue];
                    stationInfo.longitude = [stationDict[@"info"][@"location"][0] doubleValue];
                    stationInfo.latitude = [stationDict[@"info"][@"location"][1] doubleValue];
                    stationInfo.totalCount = [stationDict[@"info"][@"total"] integerValue];
                    stationInfo.remainCount = [stationDict[@"count"] intValue];
                    tempDict[stationInfo.stationID] = stationInfo;
                }
                [HZTBikeStationManager sharedManager].stationDictionary = tempDict;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationCircumInfoGetSuccess object:nil];
                });
            }
            @catch (NSException *exception) {
                DebugLog(@"didFailedGetCircumInfo: %@", exception.description);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationCircumInfoGetFailed object:nil];
                });
            }
            @finally {
                
            }
        }
    }];
}

- (void)getStationInfo:(NSString *)stationID
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/bike/station?id=%@", ServerURL, stationID]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setTimeoutInterval:10.0];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) {
            DebugLog(@"Httperror:%@%ld", connectionError.localizedDescription, (long)connectionError.code);
            
        }
        else
        {
            NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@", responseString);
            
            @try {
//                NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            }
            @catch (NSException *exception) {
                DebugLog(@"didFailedGetCircumInfo: %@", exception.description);
                
            }
            @finally {
                
            }
        }

    }];
}

- (BOOL)isNetworkAvailable
{
    CFNetDiagnosticRef diag;
    diag = CFNetDiagnosticCreateWithURL (NULL, (__bridge CFURLRef)[NSURL URLWithString:@"http://www.hztrip.org"]);
    CFNetDiagnosticStatus status;
    status = CFNetDiagnosticCopyNetworkStatusPassively (diag, NULL);
    CFRelease (diag);
    
    if ( status == kCFNetDiagnosticConnectionUp )
    {
        NSLog (@"Connection is up");
        return YES;
    }
    else {
        NSLog (@"Connection is down");
        return NO;
    }
}

@end
